package club.xyes.zkh.ecommerce.service.impl;

import club.xyes.zkh.ecommerce.commons.entity.Commodity;
import club.xyes.zkh.ecommerce.commons.entity.CommodityImage;
import club.xyes.zkh.ecommerce.commons.properties.WebsiteConfigurationProperties;
import club.xyes.zkh.ecommerce.commons.util.MultipartFileUtil;
import club.xyes.zkh.ecommerce.dao.mapper.CommodityImageMapper;
import club.xyes.zkh.ecommerce.service.CommodityImageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * Create by 郭文梁 2019/4/17 0017 10:26
 * CommodityImageServiceImpl
 * 商品图片相关业务行为实现
 *
 * @author 郭文梁
 * @data 2019/4/17 0017
 */
@Service
@Slf4j
public class CommodityImageServiceImpl extends BaseServiceImpl<CommodityImage> implements CommodityImageService {
    private final CommodityImageMapper mapper;
    private final WebsiteConfigurationProperties websiteConfigurationProperties;

    @Autowired
    public CommodityImageServiceImpl(CommodityImageMapper mapper,
                                     WebsiteConfigurationProperties websiteConfigurationProperties) {
        super(mapper);
        this.mapper = mapper;
        this.websiteConfigurationProperties = websiteConfigurationProperties;
    }

    @Override
    public boolean existsByCommodityId(Integer commodityId) {
        CommodityImage query = new CommodityImage();
        query.setCommodityId(commodityId);
        return mapper.selectCount(query) > 0;
    }

    @Override
    public void deleteByCommodityId(Integer commodityId) {
        CommodityImage query = new CommodityImage();
        query.setCommodityId(commodityId);
        int rows = mapper.delete(query);
        log.debug("Delete {} CommodityImage", rows);
    }

    @Override
    public CommodityImage create(Commodity commodity, MultipartFile imageFile) throws IOException {
        String path = getImagePath();
        String filename = MultipartFileUtil.save(imageFile, path);
        CommodityImage image = new CommodityImage();
        image.setAbsolutely(false);
        image.setImageUrl(filename);
        image.setCommodityId(commodity.getId());
        image.setCommodity(commodity);
        return save(image);
    }

    /**
     * 获取商铺图片文件保存路径
     *
     * @return 路径
     */
    private String getImagePath() {
        return websiteConfigurationProperties.getStaticFilePath() +
                websiteConfigurationProperties.getCommodityImagePath();
    }
}
